package com.jar.netty_demo.NIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * scattering：将效据写入到助buffer时，可以采用buffer效组，依次写入
 * Gathering:Mbuffer读取效摇时，可以采用buffer囊组，依次读
 * NIO支持多个Buffer读写操作
 */
public class ScatteringDemo {
    public static void main(String[] args) throws IOException {
        //NIO使用的是ServerSocketChannel和SocketChannel  网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket serverSocket = new ServerSocket();
        //绑定端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7777);
        serverSocketChannel.bind(inetSocketAddress);
//        serverSocketChannel.socket().bind(inetSocketAddress);
        //创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);
        //等客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        int messageLength = 8;
        //循环读取
        while (true) {
            int byteRead = 0;
            while (byteRead < messageLength) {
                long read = socketChannel.read(byteBuffers);
                byteRead += read; // 累计读取的字节数
                System.out.println("byteRead=" + byteRead);
                //使用流打印，看看当前的这个buffer的position和limit
                Arrays.stream(byteBuffers).map(buffer -> "position=" + buffer.position() + ",limit=" + buffer.limit()).forEach(System.out::println);
            }
            //将所有的buffer进行flip
            Arrays.stream(byteBuffers).forEach(ByteBuffer::flip);
            //将数据读出显示到客户端
            long byteWirte = 0;
            while (byteWirte < messageLength) {
                long write = socketChannel.write(byteBuffers);
                byteWirte += write;
            }
            //将所有的buffer进行clear
            Arrays.stream(byteBuffers).forEach(ByteBuffer::clear);
            System.out.println("byteRead:="+byteRead+"byteWrite="+byteWirte+"messagelength"+messageLength);
        }
    }
}
